<?php

namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\exception\UserException;
use app\api\model\User as UserModel;
use app\api\service\Token;
use app\api\validate\AddressNew;
use app\api\exception\SuccessMessage;
use function input;

class Address extends BaseController
{

    protected $beforeActionList = [
        'checkPrimaryScope' => [ 'only' => 'createOrUpdateAddress,getUserAddress' ]
    ];

    /**
     * 更新或者创建用户收获地址
     */
    public function createOrUpdateAddress()
    {
        $validate = new AddressNew();
        $validate->goCheck();
        $uid = Token::getCurrentUid();
        $address_arr = $validate->getDataByRule(input('post.'));
        $user_model = UserModel::get($uid);
        if (empty($user_model))
        {
            throw new UserException();
        }
        if (!empty($user_model->address))
        {
            $user_model->address->save($address_arr);
        }
        else
        {
            $user_model->address()->save($address_arr);
        }

        return new SuccessMessage();
    }

    /**
     * 获取用户地址信息
     * @return UserAddress
     * @throws UserException
     */
    public function getUserAddress()
    {
        $uid = Token::getCurrentUid();
        $user_model = UserModel::get($uid);
        if (empty($user_model))
        {
            throw new UserException();
        }
        $address_model = $user_model->address;
        if (empty($address_model))
        {
            $option = [
                'msg' => '用户地址不存在',
                'errorCode' => 60001
            ];
            throw new UserException($option);
        }

        return $address_model;
    }

}
